﻿# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import scrolledtext

def adjust_number(result):
    """调整结果到1-49范围内"""
    return result + 49 if result < 1 else result - 49 if result > 49 else result

def calculate_results(initial_numbers, step_numbers):
    """计算结果集合（保持差值顺序）"""
    return {
        num: [adjust_number(num + step) for step in step_numbers]
        for num in initial_numbers
    }

class DataProcessor:
    def __init__(self):
        self.data = []
        self.raw_data = []
    
    def load_from_text(self, text_data):
        """从文本数据加载"""
        try:
            lines = text_data.strip().split('\n')
            self.raw_data = []
            
            for line in lines:
                numbers = list(map(int, line.replace(',', ' ').replace(';', ' ').split()))
                if len(numbers) != 7:
                    raise ValueError(f"每期必须包含7个数字，当前行：{line}")
                self.raw_data.append(numbers)
            
            if len(self.raw_data) < 2:
                raise ValueError("至少需要2期数据")
            
            self.data = self.raw_data  # 保持原始顺序（最新数据在最前面）
            return True
        except Exception as e:
            raise ValueError(f"数据加载失败: {str(e)}")

class LotteryApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("智能彩票分析系统 v3.2")
        self.geometry("1000x800")
        self.processor = DataProcessor()
        
        self.create_widgets()
        self.center_window()

    def center_window(self):
        self.update_idletasks()
        width = self.winfo_width()
        height = self.winfo_height()
        x = (self.winfo_screenwidth() // 2) - (width // 2)
        y = (self.winfo_screenheight() // 2) - (height // 2)
        self.geometry(f'{width}x{height}+{x}+{y}')

    def create_widgets(self):
        # 输入区域
        input_frame = tk.LabelFrame(self, text="数据输入区（最新一期在最前面）")
        input_frame.pack(pady=5, padx=10, fill=tk.X)
        
        self.input_area = scrolledtext.ScrolledText(input_frame, width=100, height=10)
        self.input_area.pack(padx=5, pady=5)

        # 控制面板
        control_frame = tk.Frame(self)
        control_frame.pack(pady=5, fill=tk.X)
        
        # 参数输入区
        param_frame = tk.Frame(control_frame)
        param_frame.pack(side=tk.LEFT, padx=10)
        
        tk.Label(param_frame, text="分析期数：").grid(row=0, column=0, sticky="w")
        self.analyze_entry = tk.Entry(param_frame, width=8)
        self.analyze_entry.grid(row=0, column=1, padx=2)
        self.analyze_entry.insert(0, "10")
        
        tk.Label(param_frame, text="最小出现次数：").grid(row=0, column=2, padx=(10,2))
        self.count_entry = tk.Entry(param_frame, width=8)
        self.count_entry.grid(row=0, column=3, padx=2)
        self.count_entry.insert(0, "9")
        
        # 按钮区
        btn_frame = tk.Frame(control_frame)
        btn_frame.pack(side=tk.LEFT, padx=10)
        
        self.btn_load = tk.Button(btn_frame, text="加载数据", command=self.load_data)
        self.btn_analyze = tk.Button(btn_frame, text="开始分析", command=self.analyze)
        self.btn_load.pack(side=tk.LEFT, padx=5)
        self.btn_analyze.pack(side=tk.LEFT, padx=5)

        # 数据预览
        data_frame = tk.LabelFrame(self, text="已加载数据预览（最新在最前）")
        data_frame.pack(pady=5, padx=10, fill=tk.BOTH, expand=True)
        self.data_display = scrolledtext.ScrolledText(data_frame, width=100, height=10)
        self.data_display.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)

        # 结果展示
        result_frame = tk.LabelFrame(self, text="分析结果")
        result_frame.pack(pady=5, padx=10, fill=tk.BOTH, expand=True)
        self.result_display = scrolledtext.ScrolledText(result_frame, width=100, height=20)
        self.result_display.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)

    def load_data(self):
        """加载数据"""
        try:
            raw_text = self.input_area.get("1.0", tk.END)
            if self.processor.load_from_text(raw_text):
                self.show_data()
                self.show_message("数据加载成功！", "green")
        except Exception as e:
            self.show_message(str(e), "red")

    def show_data(self):
        """显示所有加载数据"""
        self.data_display.delete(1.0, tk.END)
        for i, period in enumerate(self.processor.raw_data):
            self.data_display.insert(tk.END, 
                f"第{i+1:03}期: {'  '.join(map(str, period))}\n")

    def analyze(self):
        """执行分析流程"""
        if not self.processor.data:
            self.show_message("请先加载数据！", "red")
            return
        
        try:
            self.result_display.delete(1.0, tk.END)
            self.result_display.insert(tk.END, "正在分析...\n")
            self.update()
            
            # 获取分析参数
            try:
                n = int(self.analyze_entry.get())
                if n < 2 or n > len(self.processor.data):
                    n = min(len(self.processor.data), max(n, 2))
                    self.show_message(f"自动调整为分析{n}期数据", "blue")
            except:
                n = len(self.processor.data)
                self.show_message(f"使用全部{n}期数据进行分析", "blue")
            
            try:
                min_count = int(self.count_entry.get())
                if min_count < 1:
                    min_count = 9
                    self.show_message("出现次数不能小于1，已重置为9", "blue")
            except:
                min_count = 9
                self.show_message("使用默认最小出现次数9", "blue")

            selected_data = self.processor.data[:n]
            
            # 计算差值集合（保持顺序）
            transitions = []
            for i in range(len(selected_data)-1):
                current = selected_data[i]    # 最新一期
                next_period = selected_data[i+1]  # 前一期
                diffs = {(a - b) % 49 for a in current for b in next_period}
                transitions.append(diffs)

            # 统计差值出现次数（保持顺序统计）
            counter = {}
            for t in transitions:
                for d in t:
                    counter[d] = counter.get(d, 0) + 1

            # 筛选有效差值（按出现次数排序）
            valid_diffs = sorted(
                [d for d, count in counter.items() if count >= min_count],
                key=lambda x: (-counter[x], x)  # 按频率降序，数值升序
            )
            
            # 生成预测结果（保持差值顺序）
            latest_period = selected_data[0]
            results = calculate_results(latest_period, valid_diffs)

            self.show_results(valid_diffs, results, min_count)
        except Exception as e:
            self.show_message(f"分析失败: {str(e)}", "red")

    def show_results(self, diffs, results, min_count):
        """显示分析结果（保持差值顺序）"""
        self.result_display.delete(1.0, tk.END)
        
        self.result_display.insert(tk.END, f"有效差值集合（出现次数≥{min_count}）:\n")
        self.result_display.insert(tk.END, ", ".join(map(str, diffs)) if diffs else "无符合条件差值")  # 修正括号
        
        self.result_display.insert(tk.END, "\n\n预测号码集合（按差值顺序排列）:\n")
        if not diffs:
            self.result_display.insert(tk.END, "没有有效差值，无法生成预测号码")
            return
        
        for num, values in results.items():
            # 保持原始顺序显示
            self.result_display.insert(tk.END, 
                f"▪ 基准号码 {num:2} → 预测结果: {values}\n")  # 移除sorted()

    def show_message(self, message, color="black"):
        """显示状态信息"""
        self.result_display.tag_config(color, foreground=color)
        self.result_display.insert(tk.END, message + "\n", color)
        self.result_display.see(tk.END)

if __name__ == "__main__":
    app = LotteryApp()
    app.mainloop()